<?php
namespace app\api\controller;

use app\common\controller\ApiBase;
use think\Cache;
use think\Db;



header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Credentials:true");
header("Access-Control-Max-Age:3600");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken,Token,ID");
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS');


class Index extends ApiBase
{
    private $smsapi = "http://api.smsbao.com/";
    private $user = '15698254063';//短信平台帐号
    private $pass ;
    protected $statusStr = array(
        "0" => "发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
      protected function _initialize(){
        parent::_initialize();
        $this->api=new ApiBase();
        $this->pass = md5('abc123');//短信平台密码
    }
//public function test(){
//    $star = '';
//    $info['card_username'] = '一二三';
//    //名字打码开始
//    $shop_type_num = mb_strlen($info['card_username'],'UTF-8');
//    for ($i=1;$i<$shop_type_num;$i++){
//        $star=$star.'*';
//    }
//    $info['card_username']=substr_replace($info['card_username'],$star,0,($shop_type_num-1)*3);
//    return json($info);
//}
    /**
     * 获取验证码
     * @param $m int 手机号
     * @param $a string 参数
     * @return \think\response\Json
     */
    public function get_code()
    {
        if($this->request->isPost()) {
            $data = $this->request->param();
            if (!isset($data['mobile']) || !isset($data['type'])) {
                return $this->api->splash(0, '信息不完整，请认真填写');
            }
            $mobile = $data['mobile'];
            $type = $data['type'];
            if (!$this->check_mobile($mobile)) {
                return $this->api->splash(0, '手机号格式有误，请重新填写');
            }
            if ($type == 'zhuce') {
                $f = Db::name('user')->where(['mobile' => $mobile])->find();
                if ($f) {
                    return $this->api->splash(0, '此手机号已被注册');
                }
            }
            $s = Db::name('send_msg')->where(['mobile'=>$mobile,'type'=>$type])->order('id desc')->find();
            if((time()-$s['add_time'])<=300){
                return $this->api->splash(0, '验证码已发送，有效期五分钟，请不要重复申请');
            }

            $code = rand(1000, 9999);
            $res = $this->send_msg($mobile, $code);
            if (0 == $res) {
                Db::name('send_msg')->insertGetId(['mobile'=>$mobile,'code'=>$code,'status'=>$res,'type'=>$type,'add_time'=>time()]);
                Cache::set($type . $mobile, $code, 300);
                return $this->api->splash(1, $this->statusStr[$res]);
            } else {
                return $this->api->splash(0, $this->statusStr[$res]);
            }
        }else{
            return $this->api->splash(0, '请求错误');
        }
        
    }
  	/**
     * 发送短信验证码
     */
    private function send_msg($mobile,$code)
    {
        $content="[德信商城]尊敬的用户，您的验证码是".$code."，请于5分钟内正确输入。如非本人操作，请忽略此短信。";//要发送的短信内容
        $sendurl = $this->smsapi."sms?u=".$this->user."&p=".$this->pass."&m=".$mobile."&c=".urlencode($content);
        return file_get_contents($sendurl);
    }

    /**
     * 手机号验证
     */
    private function check_mobile($mobile){
        $rule = '/^0?(13|14|15|17|18)[0-9]{9}$/';
        $result = preg_match($rule, $mobile);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * 注册页，根据id找用户手机号
     */
    public function get_mobile()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if(!isset($data['up_user_id'])){
                return $this->api->splash(0,'信息不完整，请认真填写');
            }
            $up_user = Db::name('user')->where('id',$data['up_user_id'])->value('mobile');

            if(!empty($up_user)){
                $send = [
                    'mobile'=>$up_user
                ];
                return $this->api->splash(1,'查找成功',$send);
            }else{
                return $this->api->splash(0,'没有数据');
            }
        }
    }
  	/**
     * 注册
     */
    public function register()
    {
      	if ($this->request->isPost()) {
            $data = $this->request->param();
          	if(!isset($data['mobile'])||!isset($data['code'])||!isset($data['password'])||!isset($data['in_user_mobile'])){
              	return $this->api->splash(0,'信息不完整，请认真填写');
            }
            if($data['code'] != Cache::get("zhuce".$data['mobile'])){
                return $this->api->splash(0,'验证码错误');
            }
            $up_user = Db::name('user')->where('mobile',$data['in_user_mobile'])->value('id');
            if(empty($up_user)){
                return $this->api->splash(0,'邀请人不存在，请重新确认');
            }
            $save['in_user_id'] = $up_user;
            $save['password'] = md5($data['password']);
            $save['mobile'] = $data['mobile'];
          	$save['username'] = '用户'.$data['mobile'];
            $save['create_time'] = date('Y-m-d H:i:s',time());
            $r = Db::table('os_user')->insertGetId($save);
          	if($r){
                Cache::clear("zhuce".$data['mobile']);
                $token = $this->api->set_token($r,$data['mobile']);
                $info = Db::table('os_user')->where(['id' => $r])->field('id,username,mobile,image,token,level')->find();
                $info['img_url'] = 'http://' . $_SERVER['SERVER_NAME'] . '/public/';
              	return $this->api->splash(1,'注册成功',$info);
            }else{
              	return $this->api->splash(0,'出错了，请稍后重试');
            }
        }
    }

//  	/**
//     * 短信登录
//     */
//    public function code_login()
//    {
//      	$chlid=new Index();
//        return  $chlid->test('sss');
//    }
  
  	/**
     * 帐号密码登录
     */
    public function login()
    {
        if ($this->request->isPost()) {
            $data = request()->param();
            if (!$data['mobile']) {
                return $this->api->splash(0, '请输入手机号');
            }
            if (!$data['password']) {
                return $this->api->splash(0, '请输入密码');
            }
            $find = Db::table('os_user')->where(['mobile' => $data['mobile']])->find();
            if (empty($find)) {
                return $this->api->splash(0, '帐号不存在，请检查帐号是否正确');
            } else {
                $password = md5($data['password']);
                if ($find['password'] != $password) {
                    return $this->api->splash(0, '密码错误，请检查帐号密码是否填写正确');
                }
            }
            if ($find['status'] != 1) {
                return $this->api->splash(0, '帐号异常，已禁止登录，请联系管理员');
            }

            $last_login_time = date('Y-m-d H:i:s', time());
            Db::table('os_user')->update(['last_login_time' => $last_login_time, 'id' => $find['id']]);
            //给token
            $token = $this->api->set_token($find['id'], $find['mobile']);
            $info = Db::table('os_user')->where(['mobile' => $data['mobile']])->field('id,username,mobile,image,token,level')->find();
            $info['img_url'] = 'http://' . $_SERVER['SERVER_NAME'] . '/public/';
            return $this->api->splash($token['Status'], $token['Message'], $info);
        }else{
            return $this->api->splash(0, '请求错误');
        }
    }
//  	// 获取access_token
//	public function getToken()
//	{
//		$user = new User;
//		$appid="wxcff4e80cfcdeedf1";
//	    $appsecret = "00bb0fa00b1bfe2d273dba9a5b0349a7";
//		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
//	    $res=json_decode($user->curl_get($url));
//	    return json($res);
//	}
//  	/**
//     * 微信登录
//     */
//	public function wx_login($code,$username = 0,$photo = 0,$sex = 0)
//    {
//		$data=$this->request->post();
//		$code = $data['code'];//小程序传来的code值
//		$appid = 'wxcff4e80cfcdeedf1';//小程序的appid
//		$appSecret = '00bb0fa00b1bfe2d273dba9a5b0349a7';// 小程序的$appSecret
//		$wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
//		$getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid，appsecret，code拼接到url里
//		$user = new User;
//		$result = $user->curl_get($getUrl);//请求拼接好的url
//		$wxResult = json_decode($result, true);
//		if (empty($wxResult)) {
//			return json('获取openid时异常，微信内部错误');
//		} else {
//			$loginFail = array_key_exists('errcode', $wxResult);
//			if ($loginFail) {//请求失败
//				return json($wxResult);
//			} else {//请求成功
//				$openid = $wxResult['openid'];
//				$where['openid'] = $openid;
//				$userinfo = Db::table('os_user')->where($where)->find();
//				if($userinfo){
//					return json(['Status' => 1, 'Message' => '登录成功','Data' => $userinfo['id']]);
//				}else{
//					$where['username'] = $data['username'];
//					$where['photo'] = $data['photo'];
//					$where['sex'] = $data['sex'];
//					Db::table('os_user')->insert($where);
//					$userinfo = UserModel::where($where)->find();
//					return json(['Status' => 1, 'Message' => '注册成功','Data' => $userinfo['id']]);
//				}
//			}
//		}
//	}
    /**
     * 忘记密码
     */
    public function forget()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            if(!isset($data['mobile'])||!isset($data['code'])||!isset($data['password'])){
                return $this->api->splash(0,'信息不完整，请认真填写');
            }
            if($data['code'] != Cache::get("forget".$data['mobile'])){
                return $this->api->splash(0,'验证码错误');
            }
            $save['password'] = md5($data['password']);
            $r = Db::table('os_user')->where(['mobile'=>$data['mobile']])->update($save);
            if($r){
                Cache::clear("forget".$data['mobile']);
                $token = $this->api->set_token($r,$data['mobile']);
                $info = Db::table('os_user')->where(['mobile' => $data['mobile']])->field('id,username,mobile,image,token,level')->find();
                $info['img_url'] = 'http://' . $_SERVER['SERVER_NAME'] . '/public/';
                return $this->api->splash(1,'密码重置成功',$info);
            }else{
                return $this->api->splash(0,'出错了，请稍后重试');
            }
        }
    }

//	//php请求网络的方法
//	private function curl_get($url,$httpCode = 0) {
//		$ch = curl_init();
//		curl_setopt($ch, CURLOPT_URL, $url);
//		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//
//		//不做证书校验,部署在linux环境下请改为true
//		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
//		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
//		$file_contents = curl_exec($ch);
//		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//		curl_close($ch);
//		return $file_contents;
//	}
//// 发送验证码
//    public function Sendcode($username){
//        $statusStr = array(
//            "0" => "发送成功",
//            "-1" => "参数不全",
//            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
//            "30" => "密码错误",
//            "40" => "账号不存在",
//            "41" => "余额不足",
//            "42" => "帐户已过期",
//            "43" => "IP地址限制",
//            "50" => "内容含有敏感词"
//        );
//        $smsapi = "http://api.smsbao.com/";
//        $user = "acme"; //短信平台帐号
//        $pass = md5("acme2018"); //短信平台密码
//        $code = rand(100000,999999);
//        $content="[车饰品]尊敬的用户，您的验证码是".$code."，请于5分钟内正确输入。如非本人操作，请忽略此短信。";//要发送的短信内容
//        $phone = $username;//要发送短信的手机号码
//        $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
//        $result =file_get_contents($sendurl) ;
//        if($result == '0'){
//            $this->code_model = new CodeModel();
//            $where['username'] = $username;
//            $where['code'] = $code;
//            $where['time'] = time();
//            $this->code_model->create($where);
//            return json(array('Status' => 1,'Message' => $statusStr[$result]));
//        }else{
//            return json(array('Status' => 0,'Message' => $statusStr[$result]));
//        }
//
//    }
    //注册时协议接口
    public function agreement()
    {
        $data = Db::name('system')->field('value')->where('name', 'account_config')->find();
        $data = unserialize($data['value']);
        return $this->api->splash(1,'获取成功',$data['agreement']);
    }
    //官网信息
    public function kangxile()
    {
        $data = Db::name('system')->field('value')->where('name', 'account_config')->find();
        $data = unserialize($data['value']);
        $send = [
            'mobile'=>$data['mobile'],
            'wx'=>$data['wx']
        ];
        return $this->api->splash(1,'获取成功',$send);
    }
}
